"""
Case Type   : 系统内部使用工具
Case Name   : 执行初始化数据库命令gs_ctl init：指定参数--pwfile，
                指定的文件第一行为正确的系统管理员密码
Create At   : 2022-07-28
Owner       : liu-tong-8848
Description :
    1.创建文件，写入密码
    2.执行gs_ctl init的命令
    3.查看初始化生成的目录
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import unittest
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
import os


class Tools(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.userNode = Node('PrimaryDbUser')
        self.DB_ENV_PATH = macro.DB_ENV_PATH
        self.dir_path = os.path.join(macro.DB_INSTANCE_PATH, 'datadir')
        self.nodename = 'nodename_134'
        self.file = os.path.join(macro.DB_INSTANCE_PATH, 'ljp.txt')

    def test_systools(self):
        self.logger.info(f'-----{os.path.basename(__file__)}' + ' start-----')

        text = '--step1:创建文件，写入密码；expect：成功--'
        self.logger.info(text)
        excute_cmd0 = f'touch {self.file};' \
                      f'echo "{self.userNode.ssh_password}" >> {self.file};'
        self.logger.info(excute_cmd0)
        msg0 = self.userNode.sh(excute_cmd0).result()
        self.logger.info(msg0)

        text = '--step2:执行gs_ctl init的命令,指定参数--pwfile；expect：成功--'
        self.logger.info(text)
        excute_cmd1 = f'source {self.DB_ENV_PATH};' \
                      f'gs_ctl init -D {self.dir_path} -o ' \
                      f'"--nodename="{self.nodename}" --pwfile="{self.file}""'
        self.logger.info(excute_cmd1)
        msg1 = self.userNode.sh(excute_cmd1).result()
        self.logger.info(msg1)
        self.assertIn('Success. You can now start the database server',
                      msg1, text + '执行失败')

        text = '--step3:查看初始化生成的目录；expect：成功--'
        self.logger.info(text)
        excute_cmd2 = f'ls {self.dir_path}'
        self.logger.info(excute_cmd2)
        msg2 = self.userNode.sh(excute_cmd2).result()
        self.logger.info(msg2)
        self.assertIn('postgresql.conf' and 'pg_hba.conf', msg2, text + '执行失败')

    def tearDown(self):
        text = '--step4:清理环境；expect：成功--'
        self.logger.info(text)
        excute_cmd3 = f'rm -rf {self.dir_path};ls {self.dir_path}'
        self.logger.info(excute_cmd3)
        msg3 = self.userNode.sh(excute_cmd3).result()
        self.logger.info(msg3)
        self.assertTrue(msg3.find('No such file or directory') > -1)
        excute_cmd4 = f'rm -rf {self.file};ls {self.dir_path}'
        self.logger.info(excute_cmd4)
        msg4 = self.userNode.sh(excute_cmd4).result()
        self.logger.info(msg4)
        self.assertTrue(msg4.find('No such file or directory') > -1)
        self.logger.info(
            f'-----{os.path.basename(__file__)}' + ' end-----')

